package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;

import javax.imageio.stream.ImageInputStream;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DataSourceUtils {
    private static DruidDataSource dataSource = new DruidDataSource();
    //静态代码块，只执行一次
    static {
//读取properties属性值
        Properties prop = new Properties();
        //加载属性文件,获取输入流对象
        InputStream inputStream = DataSourceUtils.class.getClassLoader().getResourceAsStream("database.properties");

        try {
            prop.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("加载database.properties属性文件失败");
        }
        dataSource.setUrl(prop.getProperty("jdbc.url"));
        dataSource.setUsername(prop.getProperty("jdbc.username"));
        dataSource.setPassword(prop.getProperty("jdbc.password"));
        dataSource.setDriverClassName(prop.getProperty("jdbc.driverClassName"));
    }

    //返回连接池
    public static DataSource getDataSource(){

        return dataSource;

    }
    //返回连接对象
    public static Connection getConnection(){

        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("获取连接对象失败");
            return null;
        }

    }

    public static void main(String[] args) {
        Connection conn = getConnection();
        System.out.println(conn);
    }




}


